package com.ly.hotel.webagent;


import java.lang.ref.WeakReference;
import java.util.concurrent.TimeUnit;

import com.ly.hotel.adaptor.HardwareInterface;
import com.ly.hotel.common.Constants;
import com.ly.hotel.common.MyApplication;
import com.ly.hotel.common.SharedPreferencesConfig;
import com.ly.hotel.common.SysConf;
import com.ly.hotel.msgevent.CloudPlayVideoEvent;
import com.ly.hotel.msgevent.MsgDialogEvent;
import com.ly.hotel.msgevent.SendLogEvent;
import com.ly.hotel.msgevent.SyncCallEvent;
import com.ly.hotel.service.SPABackService;
import com.ly.hotel.util.HttpDownloader;
import com.ly.hotel.view.InitActivity;
import com.ly.hotel.view.floatWindows.ShuaKaFloatWin;

import de.greenrobot.event.EventBus;
import android.app.Activity;
import android.content.Context;
import android.content.Intent;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.util.Log;
import android.webkit.JavascriptInterface;
import android.webkit.WebView;

public class LyAgent {
	private Context mContext = null;
	private WebView mWebView = null;
	private String mJsFun = null;
	private boolean mBandNoRequest = false;
	private MyApplication app;
	public Integer msgDialogId;
	public boolean isDialog = false;
	public ThisHandler handler = null;
	
	public void initial(WebView webview, Context context) {
		this.mContext = context;
		this.mWebView = webview;
		this.app = (MyApplication) mContext.getApplicationContext();
		
		handler = new ThisHandler(this);
	}

	public void runJS(String jsFun) {
		if(jsFun == null || mWebView == null || handler == null){
			Log.e("LyAgent", "runJS出错了");
			return;
		}
		
		mJsFun = jsFun;
/*		handler.post(new Runnable() {
			@Override
			public synchronized void run() {
				try{
					mWebView.loadUrl("javascript: " + mJsFun);
				}catch(Exception e){
					Log.e("LyAgent", "mWebView.loadUrl出错了");
				}
			}
		});*/
		Message msg = new Message();
		Bundle bl = new Bundle();
		bl.putString("fun", mJsFun);
		msg.what = 1;
		msg.setData(bl);
		handler.sendMessage(msg);
		
	}

	// udp请求
	@JavascriptInterface
	public void udp(final String IP, final String PORT, final String request, final String responseFun,
			final String startTag, final String endTag, final String errorStartTag) {
		new Thread() {
			public void run() {
				Log.i("udp", IP + "," + PORT + "," + request + "," + responseFun + "," + startTag + "," + endTag);
				UdpCallback c = new UdpCallback() {
					@Override
					public void receive(String s) {
						//返回的数据需要去掉\r\n,\n这些字符，否则会影响数据的处理
						runJS(responseFun + "('" + s.replace("\r\n", "").replace("'", "’") + "');");
					}
				};
				try {
					int p = Integer.parseInt(PORT);
					new UdpClient(IP, p, c, startTag, endTag, errorStartTag).send(request);
				} catch (NumberFormatException n) {
					Log.i("LyAgent", "转换出错");
					runJS(responseFun + "('');");
				} catch (Exception e) {
					// TODO Auto-generated catch block
					runJS(responseFun + "('" + e.getMessage() + "');");
					e.printStackTrace();
				}
			}
		}.start();
	}

	// http get请求 (注意\\号的处理)
	@JavascriptInterface
	public void httpJsonGet(final String URL, final String request, final String responseFun) {
		new Thread() {
			public void run() {
				String str = null;
				Log.i("httpGet", request);
				str = new String(request.replace(" ", "%20"));
                String sendRes = HttpRequest.sendGet(URL, str).replace("\\", "\\\\").replace("'", "’");
				runJS(responseFun + "('" + sendRes + "');");
				//Log.i("httpGet", responseFun + "('" + sendRes + "');");
			}
		}.start();
	}

	@JavascriptInterface
	public void httpFileGet(final String URL, final String request, final String responseFun) {
		new Thread() {
			public void run() {
//				String str = null;
				Log.i("httpFileGet", URL);
//				str = new String(request.replace(" ", "%20"));
//               String sendRes = HttpRequest.sendGet(URL, str).replace("\\", "\\\\").replace("'", "’");
                String content = new HttpDownloader().download(URL);
				runJS(responseFun + "('" + content + "');");
				Log.i("httpFileGet", responseFun + "('" + content + "');");
			}
		}.start();
	}

	// http post请求 (注意\\号的处理)
	@JavascriptInterface
	public void httpJsonPost(final String URL, final String request, final String responseFun) {
		new Thread() {
			public void run() {
				String str = null;
				Log.i("httpPost", request);
				str = new String(request.replace(" ", "%20"));
                String sendRes = HttpRequest.sendPost(URL, str).replace("\\", "\\\\").replace("'", "’");
				runJS(responseFun + "('" + sendRes + "');");
				//Log.i("httpPost", responseFun + "('" + sendRes + "');");
			}
		}.start();
	}

	// 等待获取刷手牌
	@JavascriptInterface
	public void getBandNo(final String resultFun) {
		ShuaKaFloatWin.showShuakaWin();
		new Thread() {
			public void run() {
				mBandNoRequest = true;
				MyApplication.clearBandNo();
				while (MyApplication.getBandNo().equals("") && mBandNoRequest == true) {
					try {
						Thread.sleep(100);
					} catch (InterruptedException e) {
						e.printStackTrace();
					}
				}   
				
				ShuaKaFloatWin.hideShuakaWin();
				
				Log.i("getBandNo","读取卡ID:" + MyApplication.getBandNo().replace("\n", "").replace("\r", "") + "," + MyApplication.getBandNo().length());
				if (mBandNoRequest == true) {
					runJS(resultFun + "('" + MyApplication.getBandNo().replace("\n", "").replace("\r", "") + "');");
					Log.i("getBandNo", resultFun + "('" + MyApplication.getBandNo().replace("\n", "").replace("\r", "") + "');");
					MyApplication.clearBandNo();
				}
				mBandNoRequest = false;
			}
		}.start();
	}

	// 取消等待刷手牌
	@JavascriptInterface
	public void cancelBandNo() {
		mBandNoRequest = false;
	}

	// 获取电视的MAC地址，服务器的IP地址和端口号。
	@JavascriptInterface
	public void getHostAndTvInfo(final String resultFun) {
		new Thread() {
			public void run() {
				String str = MyApplication.getHostIpAndPort().replace(":", ",");
				String mac = MyApplication.getMAC();
				runJS(resultFun + "('" + mac + "," + str + "');");
				Log.i("getHostAndTvInfo", resultFun + "('" + mac + "," + str + "');");
			}
		}.start();
	}
	
	@JavascriptInterface
	public void hideJishiWorkWindow() {
		Log.i("LyAgent", "接口那家伙要隐藏技师上下钟窗口!");
//		app.setJishiPopWindowsShow(false);
		/*MyApplication.getContext().sendBroadcast(new Intent(Constants.Broadcast.CALL_JISHI_POP_WINDOW).putExtra("flag",
				Constants.JISHI_WORK_CLOSE));*/
	}
	
	@JavascriptInterface
	public void myDebug(final String msg) {
		Thread task = new Thread() {
			public void run() {
				Log.i("myDebug", msg);
			}
		};
		
		SPABackService.getThreadPool().schedule(task, 0, TimeUnit.MILLISECONDS);
	}
    
	//延时弹窗，返回这个弹窗在队列里的id
	@JavascriptInterface
	public String showMsgDialog(final String msg, final String delayTime) {
		SPABackService.msgActivityid++;
		msgDialogId = SPABackService.msgActivityid;
		Log.i("LyAgent", "显示弹出,id：" + msgDialogId.toString());
		EventBus.getDefault().post(new MsgDialogEvent(msgDialogId, msg, Integer.parseInt(delayTime),MsgDialogEvent.ACTION_SHOW));
		return msgDialogId.toString();
	}
	//通过id将还没有显示的弹窗从队列中去掉，如果已经显示了的，也可以通过这个方法关闭
	@JavascriptInterface
	public void closeMsgDialog(final String id) {
		try{
			Integer diaglogId = Integer.parseInt(id);
			EventBus.getDefault().post(new MsgDialogEvent(diaglogId, "", 0 ,MsgDialogEvent.ACTION_CLOSE));
		}catch(Exception e){
			
		}
	}
	
	// 呼叫灯接口
	@JavascriptInterface
	public void turnOnLight(String str) {
		if(SharedPreferencesConfig.getAppMode(app.getBaseContext()).equals("hotel")){
			EventBus.getDefault().post(new SyncCallEvent());
		}
		if (str.equals("on")) {
			app.setLight(true);
		} else if (str.equals("off")) {
			app.setLight(false);
		}
	}

	// 呼叫灯接口
	@JavascriptInterface
	public void turnOnLightHd(String str) {
		if (str.equals("on")) {
			app.setLightHd(true);
		} else if (str.equals("off")) {
			app.setLightHd(false);
		}
	}
	
	// 呼叫灯接口
	@JavascriptInterface
	public void turnOnLightCustom(String str) {
		if (str.equals("on")) {
			HardwareInterface.setCardLed(app.getBaseContext(), true);
		} else if (str.equals("off")) {
			HardwareInterface.setCardLed(app.getBaseContext(), false);
		}
	}
	
	@JavascriptInterface
	public void showSettingWindow() {
		//new Thread() {
		//	public void run() {
//				TouchUtil.sendKeyCode(MyKeyEventCode.KEYCODE_SET,200, true);
		//	}
		//}.start();
		if(SharedPreferencesConfig.getAppMode(MyApplication.getContext()).equals("hotel") || SharedPreferencesConfig.getAppMode(MyApplication.getContext()).equals("spa_pro")){
			Intent intent = new Intent(Intent.ACTION_MAIN);
			intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
			intent.setClassName("com.ly.hotel", "com.ly.hotel.view.setting.UserGuideActivity");
			MyApplication.getContext().startActivity(intent);
		}
	}
	
	@JavascriptInterface
	public void checkPluginAuthCode(String code){
	}
	
	//自杀
	@JavascriptInterface
	public void finish(){
		if(isDialog){
			Log.i("lyAgent", "关闭弹窗,id:" + msgDialogId);
			EventBus.getDefault().post(new MsgDialogEvent(msgDialogId, "" , 0, MsgDialogEvent.ACTION_CLOSE));
		}else{
			Activity activity = (Activity) mContext;
			activity.finish();
		}
	}
	
	//通过ID来关闭指定的弹窗
	@JavascriptInterface
	public void closeMsgDialogById(String str){
		Integer id = Integer.getInteger(str);
		EventBus.getDefault().post(new MsgDialogEvent(id, "", 0, MsgDialogEvent.ACTION_CLOSE));
	}
	
	@JavascriptInterface
	public String getMsgDialogId(){
		return msgDialogId.toString();
	}
	
	@JavascriptInterface
	public String getApkVersion() { 
		if(MyApplication.shareUid == null || !MyApplication.shareUid.equals("android.uid.system")){
			return "v" + MyApplication.getApkVersion() + ".noroot" + "(" + app.getSystemVersion() + ",v" + Constants.LYAGENT_VERSION + ")"; 
		}else{
			return "v" + MyApplication.getApkVersion() + "(" + app.getSystemVersion() + ",v" + Constants.LYAGENT_VERSION + ")"; 
		}
	}
	
	@JavascriptInterface
	public String getApkVersion2() { 
		if(MyApplication.shareUid == null || !MyApplication.shareUid.equals("android.uid.system")){
			return "v" + MyApplication.getApkVersion() + ".noroot"; 
		}else{
			return "v" + MyApplication.getApkVersion() ; 
		}
	}
	
	@JavascriptInterface
	public String getSysVersion() { 
		return "" + app.getSystemVersion(); 
	}
	
	@JavascriptInterface
	public String isSupportRemote() { 
		if(MyApplication.isSupportRemote){
			return "true"; 
		}else{
			return "false"; 
		}
	}
	
	@JavascriptInterface
	public String getAuthInfo(){
		return app.getAuthToCompany();
	}
	
	@JavascriptInterface
	public void putMySpace(String key, String value){
		Log.i("MySpace", "putMySpace:" + key + "<-" + value);
		app.mySpacePutValue(key, value);
	}
	
	@JavascriptInterface
	public String getMySpace(final String key){
		Log.i("MySpace", "getMySpace:" + key + "->" + app.mySpaceGetValue(key));
		return app.mySpaceGetValue(key);
	}	
	
	@JavascriptInterface
	public void delMySpace(String key){
		Log.i("MySpace", "delMySpace:" + key);
		app.mySpaceDelKey(key);
	}  
	
	@JavascriptInterface
	public String getKeysMySpace() {
		Log.i("MySpace", "getKeysMySpace:" + app.mySpaceGenKeys());
		return app.mySpaceGenKeys();
	}
	
	@JavascriptInterface
	public String containKeysMySpace(String key) {
		Log.i("MySpace", "containKeysMySpace:" + app.mySpaceIsKey(key));
		return app.mySpaceIsKey(key);
	}
	
	@JavascriptInterface
	public void emptyMySpace() {
		Log.i("MySpace", "emptyMySpace");
		app.mySpaceEmpty();
	}
	
	@JavascriptInterface
	public void sendLog2Cloud(String msg) {
		EventBus.getDefault().post(new SendLogEvent(msg));
	}
	
	@JavascriptInterface
	public String getDeviceLanguage(){
		return MyApplication.currectLocale.toString();
	}
	
	@JavascriptInterface
	public void playVodById(String id){
		try {
			EventBus.getDefault().post(new CloudPlayVideoEvent(Integer.parseInt(id)));
		}catch (Exception se) {
			Log.e("webPlayVod", "web播放失败，id=" + id);
		}
	}

	@JavascriptInterface
	public void playVodList(String id){//所有视频的id用逗号隔开
		try {
			EventBus.getDefault().post(new CloudPlayVideoEvent(id));
		}catch (Exception se) {
			Log.e("webPlayVod", "web播放失败，id=" + id);
		}
	}

	@JavascriptInterface
	public void setConf(String name, String value){
		SysConf.extendConfPutValue(name, value);
	}

	@JavascriptInterface
	public void setMute(String enable){//所有视频的id用逗号隔开
		if(enable.equals("false")){
			HardwareInterface.setMuteFlag(false);
		} else {
			HardwareInterface.setMuteFlag(true);
		}
	}
	
	//获取整个插件的配置
	@JavascriptInterface
	public String getPluginConf(){
		return MyApplication.pluginCfg;
	}
	//获取电视位置号
	@JavascriptInterface
	public String getSeatName(){
		//返回 休息厅-A101
		return MyApplication.getDeviceInfo()
				.getCategoryName() + "-" + MyApplication.getDeviceInfo().getName();
	}
	
	private static class ThisHandler extends Handler {
		private WeakReference<LyAgent> wrActivity;

		public ThisHandler(LyAgent activity) {
			wrActivity = new WeakReference<LyAgent>(activity);
		}

		@Override
		public void handleMessage(Message message) {
			LyAgent act = wrActivity.get();
			if (act != null) {
				switch (message.what) {
				case 0:
					break;	
				case 1:
					try{
						act.mWebView.loadUrl("javascript: " + message.getData().getString("fun"));
					}catch(Exception e){
						Log.e("LyAgent", "mWebView.loadUrl出错了");
					}
					break;		
				}
			}
		}
	}   
	
	
	/*******************呼叫大屏专用接口*********************/
	@JavascriptInterface
	public String getExpConf(){
		return SysConf.expConf;
	}
	
	@JavascriptInterface
	public String getExpMac(){
		return SysConf.myMac;
	}
	
	@JavascriptInterface
	public String getExpApp(){
		return SysConf.myApp;
	}
	
	@JavascriptInterface
	public String getExpIp(){
		if(app != null){
			return app.getMyIpAddr();
		}else{
			return "";
		}
	}
	
}
